<template>
  <div>
    <el-dialog title="登陆窗口"
               :visible.sync="loginWindow"
               size="tiny">
      <div>
        <valid :inputType="'account'" ref="account"></valid>
        <valid :inputType="'password'" ref="password"></valid>
      </div>
      <div class="login-link">
        <a href="javascript:void(0)" class="left">忘记密码</a>
        <a href="javascript:void(0)">立即注册</a>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="login()" :disabled="submitDisabled">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import { LOGIN_URL } from './../../common/js/url'
  import { IS_SHOW_LOGIN_WINDOW, SET_PERSONAL_INFO } from './../../store/mutation-types'
  import { mapGetters } from 'vuex'
  export default {
    computed: mapGetters({
      showLoginWindow: IS_SHOW_LOGIN_WINDOW
    }),
    data () {
      return {
        loginWindow: false,
        submitDisabled: false
      }
    },
    methods: {
      init () {
        this.$refs.account.initialize()
        this.$refs.password.initialize()
      },
      close () {
        this.loginWindow = false
        this.$store.dispatch(IS_SHOW_LOGIN_WINDOW, false)
      },
      login () {
        let accountPass = this.$refs.account.pass
        let passwordPass = this.$refs.password.pass
        if (!accountPass || !passwordPass) {
          this.$refs.account.accountValid()
          this.$refs.password.passwordValid()
          return
        }

        let account = this.$refs.account.value
        let password = this.$refs.password.value
        this.$http.get(LOGIN_URL, {params: {account: account, password: password}}).then(response => {
          if (response.data.success) {
            this.$store.dispatch(SET_PERSONAL_INFO, response.data.data)
            this.loginWindow = false
          } else {
            alert('登陆失败,请输入正确的账号密码!')
          }
        })
      }
    },
    watch: {
      'showLoginWindow' (newValue, oldValue) {
        this.loginWindow = this.showLoginWindow
      },
      'loginWindow' (newValue, oldValue) {
        if (this.$refs.account) {
          this.init()
        }
        if (!newValue) {
          this.$store.dispatch(IS_SHOW_LOGIN_WINDOW, false)
        }
      }
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import "../../common/style/common.styl";
  @import "login.styl";
</style>
